import React, { useState, useEffect } from 'react';
import EnergyChart from '../components/EnergyChart';
import DataTable from '../components/DataTable.js';
import Chart from '../components/Chart.js';
import EChartBar from '../components/EChartBar.js';
import EChartStackedLine from '../components/EChartStackedLine.js';
import MarketChart from '../components/MarketChart.js';
import MarketStatusIndicator from '../components/MarketStatusIndicator.jsx';
import { 
  fetchMarketIndices, 
  fetchKLineData, 
  fetchMinuteData,
  fetchWeeklyKLineData,
  fetchMonthlyKLineData,
  fetchMarketDistribution,
  fetchMarketTrend
} from '../services/Api.js';
import '../styles/Home.css';
import { ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import MarketDataWatcher from '../components/MarketDataWatcher.tsx';


const Home = () => {
  // const [marketData, setMarketData] = useState([]);
  const [indicesData, setIndicesData] = useState(null);
  const [loading, setLoading] = useState(true);
  // 移除标签页状态
  // 选择图表类型以及指数名称，对应各个按钮操作，切换这两个变量状态
  const [chartType, setChartType] = useState('today'); // 'today', '5day', 'day', 'week', 'month'
  const [selectedIndex, setSelectedIndex] = useState('000001.SH'); // 默认上证指数
  // K线初始化状态
  const [candlestickDates, setCandlestickDates] = useState([]);
  const [candlestickData, setCandlestickData] = useState([]);

  // 分时数据状态
  const [timelineData, setTimelineData] = useState({
    today: null,
    fiveDay: null,
    current: null
  });

  // 涨跌分布数据
  const [marketDistributionData, setMarketDistributionData] = useState({
    categories: [],
    values: [],
    trade_date: null
  });
  
  // 市场趋势数据（近60个交易日的上涨/下跌家数）
  const [marketTrendData, setMarketTrendData] = useState({
    dates: [],
    upCount: [],
    downCount: []
  });

  // 示例收益趋势数据
  const [profitTrendData, setProfitTrendData] = useState([
    10.2, 12.5, 15.8, 14.3, 16.7, 18.2, 17.5, 19.8, 21.3, 20.5, 22.8, 24.5
  ]);

  // 获取涨跌分布数据和市场趋势数据
  useEffect(() => {
    const fetchMarketData = async () => {
      try {
        // 获取涨跌分布数据
        const distributionData = await fetchMarketDistribution();
        console.log('distributionData:', distributionData)
        if (distributionData && distributionData.distribution) {
          setMarketDistributionData({
            categories: distributionData.distribution.map(item => item.range),
            values: distributionData.distribution.map(item => item.count),
            trade_date: distributionData.trade_date
          });
        }

        // 获取市场趋势数据
        const trendData = await fetchMarketTrend();
        if (trendData && trendData.trend) {
          setMarketTrendData({
            dates: trendData.trend.map(item => item.date),
            upCount: trendData.trend.map(item => item.up_count),
            downCount: trendData.trend.map(item => item.down_count)
          });
        }
      } catch (error) {
        console.error('Error fetching market data:', error);
      }
    };

    fetchMarketData();
  }, []);

  useEffect(() => {
    const loadData = async () => {
      try {
        setLoading(true);
        // 获取市场数据
        const indicesDataRes = await fetchMarketIndices();
        // 转换数据结构以匹配组件期望的格式
        if (indicesDataRes && indicesDataRes.latest_date && indicesDataRes.indices) {
          const formattedData = {
            date: indicesDataRes.latest_date,
            ...indicesDataRes.indices
          };
          setIndicesData(formattedData);
        } else {
          console.error('API返回的数据格式不正确:', indicesDataRes);
          setIndicesData(null);
        }

        // 获取K线数据
        const tsCode = selectedIndex; // 指数代码
        console.log('获取指数K线数据...', tsCode);
        
        // 根据当前图表类型获取相应的数据
        if (chartType === 'day' || chartType === 'week' || chartType === 'month') {
          // 获取K线数据
          let response;
          switch(chartType) {
            case 'day':
              response = await fetchKLineData(tsCode);
              break;
            case 'week':
              response = await fetchWeeklyKLineData(tsCode);
              break;
            case 'month':
              response = await fetchMonthlyKLineData(tsCode);
              break;
            default:
              response = await fetchKLineData(tsCode);
          }
          
          if (response && response.dates && Array.isArray(response.dates) && 
              response.candles && Array.isArray(response.candles)) {
            setCandlestickDates(response.dates);
            setCandlestickData(response.candles);
          }
        }
        
        // 获取分时数据
        const minuteResponse = await fetchMinuteData(tsCode);
        
        if (minuteResponse && minuteResponse.data) {
          // 处理分时数据
          const processMinuteData = (data) => {
            return {
              time: data.map(item => {
                const timeStr = item.time.split(' ')[1] || item.time;
                return timeStr.substring(0, 5); // 只保留HH:MM
              }),
              price: data.map(item => parseFloat(item.price)),
              volume: data.map(item => parseFloat(item.vol)),
              amount: data.map(item => parseFloat(item.amount)),
              preClose: data[0]?.pre_close || 0
            };
          };

          // 获取最新一天的数据
          const latestDayData = (() => {
            if (minuteResponse.data.length === 0) return [];
            
            const lastItemTime = minuteResponse.data[minuteResponse.data.length - 1].time;
            const lastDate = lastItemTime.split(' ')[0]; // 提取日期部分
            
            return minuteResponse.data.filter(item => 
              item.time.startsWith(lastDate)
            );
          })();

          // 获取5日分时数据
          const fiveDayData = minuteResponse.data;

          // 更新状态
          setTimelineData({
            today: processMinuteData(latestDayData),
            fiveDay: processMinuteData(fiveDayData),
            current: chartType === 'today' || chartType === '5day' 
              ? (chartType === 'today' ? processMinuteData(latestDayData) : processMinuteData(fiveDayData))
              : null
          });
        } else {
          console.error('分时数据格式不正确:', minuteResponse);
        }
      } catch (error) {
        console.error('获取数据失败:', error);
      } finally {
        setLoading(false);
      }
    };
    
    console.log('useEffect loadData');
    loadData();
    

  }, []);


  // 时间范围切换处理
  const handleTimeRangeChange = async (range) => {
    console.log('切换图表类型:', range, '当前selectedIndex:', selectedIndex);
    setLoading(true);
    setChartType(range); // 立即更新chartType
    
    // 如果是分时图切换
    if (range === 'today' || range === '5day') {
      // 强制清空K线数据以确保切换效果
      setCandlestickData([]);
      setCandlestickDates([]);
      
      // 获取最新分时数据
      const minuteResponse = await fetchMinuteData(selectedIndex);
      console.log('分时数据响应:', minuteResponse);
      
      if (minuteResponse && minuteResponse.data) {
        const processMinuteData = (data) => ({
          time: data.map(item => {
            const timeStr = item.time.split(' ')[1] || item.time;
            return timeStr.substring(0, 5);
          }),
          price: data.map(item => parseFloat(item.price)),
          volume: data.map(item => parseFloat(item.vol)),
          amount: data.map(item => parseFloat(item.amount)),
          preClose: data[0]?.pre_close || 0
        });

        // 获取最新一天的数据
        const latestDayData = minuteResponse.data.filter(item => 
          item.time.startsWith(
            minuteResponse.data[minuteResponse.data.length - 1].time.split(' ')[0]
          )
        );

        // 更新状态
        setTimelineData({
          today: processMinuteData(latestDayData),
          fiveDay: processMinuteData(minuteResponse.data),
          current: range === 'today' 
            ? processMinuteData(latestDayData) 
            : processMinuteData(minuteResponse.data)
        });
      }
      setLoading(false);
      return;
    }

    // 对于K线图切换，使用一个标志来确保只有最后一次请求生效
    const currentRequestId = Symbol();
    handleTimeRangeChange.currentRequestId = currentRequestId;

    try {
      // 根据图表类型获取对应的K线数据
      let response;
      switch(range) {
        case 'day':
          response = await fetchKLineData(selectedIndex);
          break;
        case 'week':
          response = await fetchWeeklyKLineData(selectedIndex);
          break;
        case 'month':
          response = await fetchMonthlyKLineData(selectedIndex);
          break;
        default:
          response = await fetchKLineData(selectedIndex);
      }
      setChartType(range); // range就是chartType
      // 只有当前请求是最后一次请求时才更新状态
      if (handleTimeRangeChange.currentRequestId === currentRequestId) {
        if (response && response.dates && Array.isArray(response.dates) && 
            response.candles && Array.isArray(response.candles)) {
          // 强制重置K线数据以触发重新渲染
          setCandlestickDates([]);
          setCandlestickData([]);
          setTimeout(() => {
            setCandlestickDates(response.dates);
            setCandlestickData(response.candles);
          }, 0);
        }
      }
    } catch (error) {
      console.error('获取数据失败:', error);
    } finally {
      if (handleTimeRangeChange.currentRequestId === currentRequestId) {
        setLoading(false);
      }
    }
  };
  // 初始化currentRequestId
  handleTimeRangeChange.currentRequestId = null;

  // 指数切换处理
  const handleIndexChange = async (tsCode) => {
    console.log(`切换指数: ${tsCode} ${chartType}`);
    setSelectedIndex(tsCode);
    setLoading(true);
    try {
      // 根据当前图表类型获取相应的数据
      if (chartType === 'day' || chartType === 'week' || chartType === 'month') {
        // 获取K线数据
        let response;
        switch(chartType) {
          case 'day':
            response = await fetchKLineData(tsCode);
            break;
          case 'week':
            response = await fetchWeeklyKLineData(tsCode);
            break;
          case 'month':
            response = await fetchMonthlyKLineData(tsCode);
            break;
          default:
            response = await fetchKLineData(tsCode);
        }
        
        if (response && response.dates && Array.isArray(response.dates) && 
            response.candles && Array.isArray(response.candles)) {
          setCandlestickDates(response.dates);
          setCandlestickData(response.candles);
        }
      }
      
      // 获取分时数据
      const minuteResponse = await fetchMinuteData(tsCode);
      if (minuteResponse && minuteResponse.data) {
        // 处理分时数据
        const processMinuteData = (data) => {
          return {
            time: data.map(item => {
              const timeStr = item.time.split(' ')[1] || item.time;
              return timeStr.substring(0, 5); // 只保留HH:MM
            }),
            price: data.map(item => parseFloat(item.price)),
            volume: data.map(item => parseFloat(item.vol)),
            amount: data.map(item => parseFloat(item.amount)),
            preClose: data[0]?.pre_close || 0
          };
        };

        // 获取最新一天的数据
        const latestDayData = (() => {
          if (minuteResponse.data.length === 0) return [];
          
          const lastItemTime = minuteResponse.data[minuteResponse.data.length - 1].time;
          const lastDate = lastItemTime.split(' ')[0]; // 提取日期部分
          
          return minuteResponse.data.filter(item => 
            item.time.startsWith(lastDate)
          );
        })();

        // 获取5日数据
        const fiveDayData = minuteResponse.data;

        // 更新状态
        const todayData = processMinuteData(latestDayData);
        const fiveDayProcessed = processMinuteData(fiveDayData);
        
        setTimelineData({
          today: todayData,
          fiveDay: fiveDayProcessed,
          current: chartType === 'today' ? todayData : 
                  chartType === '5day' ? fiveDayProcessed : null
        });
      }
    } catch (error) {
      console.error(`获取${tsCode}数据失败:`, error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="home-page">
      {/* 1. 市场概况 */}
      <section className="market-overview">
        <div className="section-header">
          <h2>市场概况 {indicesData && (
            <span className="market-date">
              {indicesData.date ? (() => {
                // 解析日期字符串，格式如"20010101"
                const dateStr = indicesData.date.toString();
                if (dateStr.length === 8) {
                  const year = dateStr.substring(0, 4);
                  const month = dateStr.substring(4, 6);
                  const day = dateStr.substring(6, 8);
                  
                  // 创建日期对象 (月份需要减1，因为JavaScript中月份从0开始)
                  const date = new Date(parseInt(year), parseInt(month) - 1, parseInt(day));
                  const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
                  const weekDay = weekDays[date.getDay()];
                  
                  // 格式化为YYYY-MM-DD格式
                  const formattedDate = `${year}-${month}-${day}`;
                  return `${formattedDate} 星期${weekDay}`;
                } else {
                  // 如果不是预期的格式，尝试直接解析
                  const date = new Date(indicesData.date);
                  const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
                  const weekDay = weekDays[date.getDay()];
                  return `${indicesData.date} 星期${weekDay}`;
                }
              })() : '--'}
            </span>
          )}</h2>
        </div>
        <div className="market-layout">
          <div className="left-panel">
            <div className="index-buttons">
              {!indicesData ? (
                <div className="loading-indices">加载指数数据中...</div>
              ) : (
                <>
                  <button 
                    className={`index-btn ${selectedIndex === '000001.SH' ? 'active' : ''}`}
                    onClick={() => handleIndexChange('000001.SH')}
                  >
                    <div className="index-name">上证指数</div>
                    <div className={`index-price ${indicesData?.shanghai?.change < 0 ? 'down' : 'up'}`}>
                      {indicesData?.shanghai?.close?.toLocaleString() || '--'}
                    </div>
                    <div className="index-change-row">
                      <span className={indicesData?.shanghai?.change < 0 ? 'down' : 'up'}>
                        {indicesData?.shanghai?.change >= 0 ? '+' : ''}
                        {indicesData?.shanghai?.change?.toFixed(2) || '--'}
                      </span>
                      <span className={indicesData?.shanghai?.change < 0 ? 'down' : 'up'}>
                        {indicesData?.shanghai?.pct_chg >= 0 ? '+' : ''}
                        {indicesData?.shanghai?.pct_chg?.toFixed(2) || '--'}%
                      </span>
                    </div>
                  </button>
                  <button 
                    className={`index-btn ${selectedIndex === '399001.SZ' ? 'active' : ''}`}
                    onClick={() => handleIndexChange('399001.SZ')}
                  >
                    <div className="index-name">深证成指</div>
                    <div className={`index-price ${indicesData?.shenzhen?.change < 0 ? 'down' : 'up'}`}>
                      {indicesData?.shenzhen?.close?.toLocaleString() || '--'}
                    </div>
                    <div className="index-change-row">
                      <span className={indicesData?.shenzhen?.change < 0 ? 'down' : 'up'}>
                        {indicesData?.shenzhen?.change >= 0 ? '+' : ''}
                        {indicesData?.shenzhen?.change?.toFixed(2) || '--'}
                      </span>
                      <span className={indicesData?.shenzhen?.change < 0 ? 'down' : 'up'}>
                        {indicesData?.shenzhen?.pct_chg >= 0 ? '+' : ''}
                        {indicesData?.shenzhen?.pct_chg?.toFixed(2) || '--'}%
                      </span>
                    </div>
                  </button>
                  <button 
                    className={`index-btn ${selectedIndex === '399006.SZ' ? 'active' : ''}`}
                    onClick={() => handleIndexChange('399006.SZ')}
                  >
                    <div className="index-name">创业板指</div>
                    <div className={`index-price ${indicesData?.gem?.change < 0 ? 'down' : 'up'}`}>
                      {indicesData?.gem?.close?.toLocaleString() || '--'}
                    </div>
                    <div className="index-change-row">
                      <span className={indicesData?.gem?.change < 0 ? 'down' : 'up'}>
                        {indicesData?.gem?.change >= 0 ? '+' : ''}
                        {indicesData?.gem?.change?.toFixed(2) || '--'}
                      </span>
                      <span className={indicesData?.gem?.change < 0 ? 'down' : 'up'}>
                        {indicesData?.gem?.pct_chg >= 0 ? '+' : ''}
                        {indicesData?.gem?.pct_chg?.toFixed(2) || '--'}%
                      </span>
                    </div>
                  </button>
                  <button 
                    className={`index-btn ${selectedIndex === '000300.SH' ? 'active' : ''}`}
                    onClick={() => handleIndexChange('000300.SH')}
                  >
                    <div className="index-name">沪深300</div>
                    <div className={`index-price ${indicesData?.csi300?.change < 0 ? 'down' : 'up'}`}>
                      {indicesData?.csi300?.close?.toLocaleString() || '--'}
                    </div>
                    <div className="index-change-row">
                      <span className={indicesData?.csi300?.change < 0 ? 'down' : 'up'}>
                        {indicesData?.csi300?.change >= 0 ? '+' : ''}
                        {indicesData?.csi300?.change?.toFixed(2) || '--'}
                      </span>
                      <span className={indicesData?.csi300?.change < 0 ? 'down' : 'up'}>
                        {indicesData?.csi300?.pct_chg >= 0 ? '+' : ''}
                        {indicesData?.csi300?.pct_chg?.toFixed(2) || '--'}%
                      </span>
                    </div>
                  </button>
                </>
              )}
            </div>
            <div className="timeline-chart">
              <MarketChart 
                chartType={chartType}
                timelineData={timelineData?.current}
                candlestickData={candlestickData}
                candlestickDates={candlestickDates}
                onChartTypeChange={handleTimeRangeChange}
                height={450}
              />
            </div>
          </div>
          <div className="right-panel">
            {/* 市场数据图表 */}
            <div className="chart-container">
              <div className="chart-pane" style={{ height: '30%' }}>
                <EChartBar 
                  data={marketDistributionData.values}
                  labels={marketDistributionData.categories}
                  trade_date = {marketDistributionData.trade_date}
                  colors={['#1cc88a', '#36cfc9', '#f6c23e', '#e74a3b', '#e74a3b']}
                  height="100%"
                />
              </div>
              <div className="chart-pane" style={{ height: '30%', paddingBottom: '0', display: 'flex', flexDirection: 'column' }}>
                {marketTrendData.upCount && marketTrendData.downCount && (
                  <EChartStackedLine 
                    data={[
                      marketTrendData.upCount,
                      marketTrendData.downCount
                    ]}
                    labels={marketTrendData.dates}
                    colors={['#e74a3b', '#1cc88a']}
                    height="100%"
                    legend={['上涨家数', '下跌家数']}
                    style={{ flex: 1, marginBottom: '0' }}
                  />
                )}
              </div>
              <div className="chart-pane" style={{ height: '40%' }}>
                <EnergyChart />
              </div>  
            </div>

            {/* 市场量能 */}
            

            
          </div>
        </div>
      </section>

      {/* 2. 主线题材 */}
      <section className="market-themes">
        <h2>主线题材</h2>
        <div className="themes-grid">
          <div className="theme-card hot">
            <h4>人工智能</h4>
            <p>热度: 85%</p>
            <p>领涨股: 科大讯飞 +8.2%</p>
            <p>资金流入: 12.5亿</p>
          </div>
          <div className="theme-card">
            <h4>新能源车</h4>
            <p>热度: 92%</p>
            <p>领涨股: 比亚迪 +6.5%</p>
            <p>资金流入: 18.3亿</p>
          </div>
          <div className="theme-card">
            <h4>半导体</h4>
            <p>热度: 78%</p>
            <p>领涨股: 中芯国际 +5.8%</p>
            <p>资金流入: 9.7亿</p>
          </div>
          <div className="theme-card">
            <h4>医药</h4>
            <p>热度: 65%</p>
            <p>领涨股: 恒瑞医药 +3.2%</p>
            <p>资金流入: 5.4亿</p>
          </div>
          <div className="theme-card">
            <h4>光伏</h4>
            <p>热度: 72%</p>
            <p>领涨股: 隆基绿能 +4.5%</p>
            <p>资金流入: 7.8亿</p>
          </div>
          <div className="theme-card">
            <h4>军工</h4>
            <p>热度: 58%</p>
            <p>领涨股: 中航沈飞 +2.9%</p>
            <p>资金流入: 4.2亿</p>
          </div>
        </div>
      </section>

      {/* 3. 重点个股 */}
      <section className="key-stocks">
        <h2>重点个股</h2>
        <DataTable 
          headers={['名称', '代码', '最新价', '涨跌幅', '成交量(万手)', '换手率', '市盈率', '主力净流入(亿)', '5日涨幅']}
          data={[
            { name: '贵州茅台', code: '600519', price: '1,850.00', change: '+2.5%', volume: '12.5', turnover: '0.8%', pe: '35.2', inflow: '3.2', fiveDay: '+8.2%' },
            { name: '宁德时代', code: '300750', price: '420.50', change: '+5.2%', volume: '28.6', turnover: '2.3%', pe: '62.8', inflow: '5.7', fiveDay: '+12.5%' },
            { name: '比亚迪', code: '002594', price: '285.30', change: '+3.8%', volume: '35.2', turnover: '3.1%', pe: '48.5', inflow: '4.2', fiveDay: '+9.6%' },
            { name: '隆基绿能', code: '601012', price: '56.80', change: '+4.5%', volume: '42.8', turnover: '2.8%', pe: '28.7', inflow: '2.9', fiveDay: '+15.3%' },
            { name: '药明康德', code: '603259', price: '98.50', change: '+1.2%', volume: '18.3', turnover: '1.5%', pe: '32.6', inflow: '1.8', fiveDay: '+5.7%' },
            { name: '中国平安', code: '601318', price: '48.60', change: '-0.5%', volume: '52.4', turnover: '1.2%', pe: '8.5', inflow: '-2.1', fiveDay: '-3.2%' },
            { name: '招商银行', code: '600036', price: '36.80', change: '+1.8%', volume: '38.7', turnover: '1.8%', pe: '7.2', inflow: '2.5', fiveDay: '+4.6%' },
            { name: '东方财富', code: '300059', price: '22.50', change: '+6.2%', volume: '62.8', turnover: '4.2%', pe: '28.3', inflow: '3.8', fiveDay: '+18.5%' }
          ]}
          loading={loading}
        />
      </section>

      {/* 4. 交易策略 */}
      <section className="trading-strategy">
        <h2>交易策略</h2>
        <div className="strategy-cards">
          <div className="strategy-card">
            <h4>趋势追踪策略</h4>
            <p>成功率: 68%</p>
            <p>年化收益: 32.5%</p>
            <p>最大回撤: 15.2%</p>
            <p>适用: 趋势行情</p>
            <button className="strategy-detail">详情</button>
          </div>
          <div className="strategy-card">
            <h4>波段操作策略</h4>
            <p>成功率: 72%</p>
            <p>年化收益: 28.7%</p>
            <p>最大回撤: 12.8%</p>
            <p>适用: 震荡行情</p>
            <button className="strategy-detail">详情</button>
          </div>
          <div className="strategy-card">
            <h4>动量轮动策略</h4>
            <p>成功率: 65%</p>
            <p>年化收益: 45.2%</p>
            <p>最大回撤: 18.6%</p>
            <p>适用: 牛市行情</p>
            <button className="strategy-detail">详情</button>
          </div>
          <div className="strategy-card">
            <h4>价值低估策略</h4>
            <p>成功率: 58%</p>
            <p>年化收益: 22.3%</p>
            <p>最大回撤: 25.4%</p>
            <p>适用: 长期投资</p>
            <button className="strategy-detail">详情</button>
          </div>
        </div>
      </section>

      {/* 5. 仓位收益 */}
      <section className="position-profit">
        <h2>仓位收益</h2>
        <div className="profit-overview">
          <div className="profit-chart">
            <Chart 
              type="line"
              data={profitTrendData}
              labels={['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']}
              colors={['#1cc88a']}
              height={200}
            />
          </div>
          <div className="position-stats">
            <div className="stat-item">
              <h4>当前仓位</h4>
              <p>68%</p>
            </div>
            <div className="stat-item">
              <h4>日收益率</h4>
              <p className="positive">+2.3%</p>
            </div>
            <div className="stat-item">
              <h4>月收益率</h4>
              <p className="positive">+15.7%</p>
            </div>
            <div className="stat-item">
              <h4>年收益率</h4>
              <p className="positive">+24.5%</p>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
};

export default Home;